package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.cache.service.ITravelStatsCacheService;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.query.TravelQueryObject;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.website.annotation.LoginUser;
import cn.wolfcode.luowowo.website.annotation.RequiredLogin;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import cn.wolfcode.luowowo.website.util.UploadUtil;
import com.github.pagehelper.PageInfo;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/travel")
public class TravelController {
    @Value("${file.dir}")
    private String dir;
    @Reference
    private ITravelService travelService;
    @Reference
    private IUserInfoService userInfoService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private IStrategyDetailService strategyDetailService;
    @Reference
    private ITravelCommentService travelCommentService;
    @Reference
    private ITravelStatsCacheService travelStatsCacheService;


    @RequestMapping("detail")
    public String getDetail(Long id, Model model){
        Travel travel = travelService.selectById(id);
        model.addAttribute("detail",travel);
        Long destId = travel.getDest().getId();
        //今日访问数+1
        travelStatsCacheService.incrNum(id,1,ITravelStatsCacheService.TRAVEL_STATS_TODAYVIEWNUM);
        //总访问数+1
        travelStatsCacheService.incrNum(id,1,ITravelStatsCacheService.TRAVEL_STATS_VIEWNUM);

        //toasts
        List<Destination> toasts = destinationService.listToasts(destId);
        model.addAttribute("toasts", toasts);
        //sds
        model.addAttribute("sds",strategyDetailService.listViewNumTop3(destId));
        //ts
        model.addAttribute("ts",travelService.listViewnumTop3(destId));
        //list 该文章的所有评论
        model.addAttribute("list", travelCommentService.listByTravelId(id));
        return "travel/detail";
    }

    @RequestMapping("")
    public String listTravel(@ModelAttribute("qo") TravelQueryObject qo,Model model){
        PageInfo<Travel> pageInfo = travelService.query(qo);
        model.addAttribute("pageInfo",pageInfo);
        return "travel/list";
    }

    //http://localhost/travel/input
    @RequestMapping("/input")
    public String input(Long id, Model model, @LoginUser UserInfo userInfo){
        if(userInfo!=null && userInfo.getId()!=null ) {
            if (id != null) {
                if (userInfo.getId().equals(travelService.selectById(id).getAuthor().getId())) {
                    model.addAttribute("tv", travelService.selectById(id));
                    model.addAttribute("dests", destinationService.list());
                    return "travel/input";
                }
            }
        }
        return "";
    }

    @RequiredLogin
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Travel travel,@LoginUser UserInfo userInfo) {
        travel.setAuthor(userInfo);
        AjaxResult ajaxResult = travelService.saveOrUpdate(travel,userInfo);
        return ajaxResult;
    }

    @RequestMapping("/getContent")
    @ResponseBody
    public Object getContent(Long id){
        return travelService.getContent(id);
    }

    @RequestMapping("/coverImageUpload")
    @ResponseBody
    public Object coverImageUpload(MultipartFile pic) {
        return UploadUtil.upload(pic, dir);

    }


    //收藏游记
    //@RequiredLogin
    @ResponseBody
    @RequestMapping("IsFavor")
    public Object updateIsFavor(@LoginUser UserInfo user, Long travelId) {
        AjaxResult result = new AjaxResult();
        if (user == null) {
            result.mark("请先登录");
            result.setCode(102);//在这个项目中约定的,表示没有登录的错误状态码
            return result;
        }
        boolean flag = travelService.iFavor(user, travelId);
        result.setSuccess(flag);
        //result.setData();
        return result;
    }


    //UME上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        java.lang.String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, dir);
        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }

    //http://localhost/travel/commentAdd
    @RequiredLogin
    @RequestMapping("commentAdd")
    public String commentAdd(TravelComment comment, Integer floor, @LoginUser UserInfo user, Model model){
        //填充用户信息
        comment.setUserId(user.getId());
        comment.setUsername(user.getNickname());
        comment.setLevel(user.getLevel());
        comment.setHeadUrl(user.getHeadImgUrl());

        //保存评论
        comment = travelCommentService.save(comment);
        //c 评论对象
        model.addAttribute("c", comment);
        //floor楼层
        model.addAttribute("floor", ++floor);
        return "travel/commentTpl";
    }
}
